package com.cuitrip.app;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.cuitrip.apiservice.BusinessHelper;
import com.cuitrip.app.init.AppInitManager;
import com.cuitrip.app.rong.RongCloudEvent;
import com.cuitrip.app.util.FontManager;
import com.cuitrip.business.location.map.GaoDeMapActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.im.CtInfoNotificationMsgItemProvider;
import com.cuitrip.im.CtInfoSystemItemProvider;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.service.BuildConfig;
import com.cuitrip.service.R;
import com.cuitrip.storage.prefrence.SettingPreferences;
import com.cuitrip.util.IResourceFetcher;
import com.cuitrip.util.MapUtil;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.track.TrackUtil;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.google.ads.conversiontracking.AdWordsConversionReporter;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.karumi.dexter.Dexter;
import com.lab.app.BaseAppLication;
import com.lab.logtrack.AppLog;
import com.lab.logtrack.DebugLogger;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.DictionaryUtil;
import com.lab.utils.ImageHelper;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.SmsSdkHelper;
import com.lab.utils.ThreadUtil;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import io.rong.imkit.RongIM;
import jonathanfinerty.once.Once;


public class MainApplication extends BaseAppLication {

    public static final String DAILY_FORCE_UPDATE = "MainApplication.DAILY_FORCE_UPDATE";
    public static final boolean IS_DEV = true;
    private static MainApplication sContext;
    public static final String BROADCAST_PERMISSION = "com.cuitrip.service.permission.broadcast";

    private int mPageWidth;
    private int mPageHeight;
    private String mChannelName;
    // App信息
    private String packageName;
    private int versionCode;
    private String versionName;
    public Bundle metaData;

    /**
     * icon 文字
     */
    private static Typeface iconFont;
    private String appVersionForApi;
    private static String sBuildtime;


    public AppEventsLogger logger;
    private RefWatcher refWatcher;
    private String cachePath;

    public static MainApplication getInstance() {
        return sContext;
    }

    public void initRongIM() {
        RongIM.init(this);
        RongIM.getInstance().registerMessageTemplate(new CtInfoSystemItemProvider());
        RongIM.getInstance().registerMessageTemplate(new CtInfoNotificationMsgItemProvider());
        RongIM.registerMessageType(CTInformationNotificationMessage.class);
    }

    private boolean getMetaBoolean(String key, boolean defaultValue) {
        if (null != metaData) {
            return metaData.getBoolean(key);
        }
        return defaultValue;
    }

    private String getMetaString(String key, String defaultValue) {
        if (null != metaData) {
            Object value = metaData.get(key);
            if (null != value)
                return value.toString();
        }
        return defaultValue;
    }

    private int getMetaInt(String key, int defaultValue) {
        if (null != metaData) {
            return metaData.getInt(key);
        }
        return defaultValue;
    }

    public static Typeface getIconFont() {
        return iconFont;
    }

    private Tracker mTracker;

    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            if (BuildConfig.DEBUG) {
                analytics.setLocalDispatchPeriod(15);
            }
            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker("UA-72089513-2");
            boolean isShowToast = SettingPreferences.getInstance().getBoolean(SettingPreferences.DebugKeys.KEY_TRACK_TOAST, false);
            TrackUtil.isShowToast = isShowToast;
        }
        return mTracker;
    }

    /**
     * 获取当前渠道号
     *
     * @return
     */
    public String getChannelName() {
        if (null == mChannelName) {
            mChannelName = getMetaString("UMENG_CHANNEL", "undefined");
        }
        return mChannelName;
    }

    public String getVersionName() {
        if (TextUtils.isEmpty(versionName)) {
            getAppInfo();
        }
        return versionName;
    }

    private void getAppInfo() {
        try {
            String pkName = this.getPackageName();
            versionName = this.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
        } catch (Exception e) {
        }
    }

    public void initRongImCallback() {
        RongIM.setGroupInfoProvider(RongCloudEvent.getInstance(), true);//设置群组信息提供者。
        RongIM.setConversationListBehaviorListener(RongCloudEvent.getInstance());
        RongIM.setGroupUserInfoProvider(RongCloudEvent.getInstance(), true);
        RongIM.setOnReceivePushMessageListener(RongCloudEvent.getInstance());
        RongIM.getInstance().getRongIMClient().setOnReceiveMessageListener(RongCloudEvent.getInstance());
        RongIM.setConversationBehaviorListener(RongCloudEvent.getInstance());
        RongIM.getInstance().getRongIMClient().setConnectionStatusListener(RongCloudEvent.getInstance());
        RongIM.getInstance().setSendMessageListener(RongCloudEvent.getInstance());
        RongIM.setUserInfoProvider(RongCloudEvent.getInstance(), true);
        RongIM.setLocationProvider(new RongIM.LocationProvider() {
            @Override
            public void onStartLocation(final Context context, final LocationCallback callback) {
//保存调用过来的回调接口在应用上下文。
                MainApplication.getInstance().setCallback(callback);
//开启定位页面。
                GaoDeMapActivity.returnForIM(context);
            }
        });

    }

    public static RongIM.LocationProvider.LocationCallback callback;

    public static RongIM.LocationProvider.LocationCallback getCallback() {
        return callback;
    }

    public static void setCallback(RongIM.LocationProvider.LocationCallback callback) {
        MainApplication.callback = callback;
    }

    public void initStictMode() {
        if (IS_DEV) {
//            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//                    .detectDiskReads()
//                    .detectDiskWrites()
//                    .penaltyDialog()
//                    .detectNetwork()   // or .detectAll() for all detectable problems
//                    .penaltyLog()
//                    .build());
//            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//                    .detectLeakedSqlLiteObjects()
//                    .detectLeakedClosableObjects()
//                    .penaltyLog()
//                    .penaltyDeath()
//                    .build());
        }
    }


    public void onCreate() {
        super.onCreate();

        Dexter.initialize(this);
        sContext = this;
        Once.initialise(this);
        if (BuildConfig.DEBUG) {
            CustomActivityOnCrash.install(this);
        }
        FontManager.init(this).inflater("font", "font/font.ttf")
                .inflater("icon", "iconfont/iconfont.ttf")
                .setDefaultType("font/font.ttf");
        AppCoreRuntime.context = this;
        initApiHost();
        initAppInfo();
        initIconFont();
        initGoogleAd();
        ImageHelper.initImageLoader(getApplicationContext());
        SmsSdkHelper.initSmsSDK(getApplicationContext());
        MapUtil.init(this);
        if ("com.cuitrip.service".equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {

            initRongIM();
            /**
             * 融云SDK事件监听处理
             *
             * 注册相关代码，只需要在主进程里做。
             */
            if ("com.cuitrip.service".equals(getCurProcessName(getApplicationContext()))) {
                initRongImCallback();
//                RongCloudEvent.init(this);
//                DemoContext.init(this);
//                Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this));
//                try {
//                    RongIM.registerMessageType(DeAgreedFriendRequestMessage.class);
//                    RongIM.registerMessageTemplate(new DeContactNotificationMessageProvider());
////                RongIM.registerMessageTemplate(new DeAgreedFriendRequestMessageProvider());
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }
        init();
        initStictMode();
        initLogger();
        if (ThreadUtil.isInUIProcess(this)){
            initFacebook();
            AppInitManager.getInstance().addPatch(this);
            initImageChooserConfig();
            initCache();
//            initLeakCanary();
        }
    }

    private void initCache() {
        try {
            cachePath = DictionaryUtil.getCacheDir(AppCoreRuntime.context).getAbsolutePath() + File.separator + "http";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getCachePath() {
        return cachePath;
    }

    private void initLeakCanary(){
        if (BuildConfig.DEBUG){
//            refWatcher = LeakCanary.install(this);
        }
    }

    public RefWatcher getRefWatcher() {
        return refWatcher;
    }

    private void initImageChooserConfig(){
        EasyImage.Configuration configuration = EasyImage.configuration(this);
        configuration.setImagesFolderName("cuitrip");
        configuration.saveInAppExternalFilesDir();
        configuration.setCopyExistingPicturesToPublicLocation(true);


    }

    private void initFacebook(){
        FacebookSdk.sdkInitialize(this);
        logger = AppEventsLogger.newLogger(this);
    }

    private void initGoogleAd() {
        // 脆饼（首次打开）
// Google Android first open conversion tracking snippet
// Add this code to the onCreate() method of your application activity

        AdWordsConversionReporter.reportWithConversionId(this.getApplicationContext(),
                "939848360", "7400COWSxmIQqOWTwAM", "0.00", false);

    }

    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initLogger() {
        if (BuildConfig.DEBUG) {
            AppLog.initLogger(new DebugLogger());
        }
    }

    private void initIconFont() {
        iconFont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
    }


    /**
     * 初始化App基本信息
     */
    private void initAppInfo() {

        // 获取App原始信息
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            packageName = packageInfo.packageName;
            versionCode = packageInfo.versionCode;
            versionName = packageInfo.versionName;
            metaData = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA).metaData;
        } catch (PackageManager.NameNotFoundException e) {
            AppLog.w(e.getMessage());
        }
    }

    private void initApiHost() {
        // BusinessHelper.API_URL = SettingPreferences.getInstance().getString(SettingPreferences.DebugKeys.KEY_API_HOST, BusinessHelper.BASE_PRE_URL);
        BusinessHelper.API_URL = SettingPreferences.getInstance().getString(SettingPreferences.DebugKeys.KEY_API_HOST, BusinessHelper.API_URL);
    }


    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    private void init() {
        DisplayMetrics displaymetrics = new DisplayMetrics();

        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(displaymetrics);
        mPageWidth = displaymetrics.widthPixels;
        mPageHeight = displaymetrics.heightPixels;
        if (mPageWidth > mPageHeight) {
            mPageWidth ^= mPageHeight;
            mPageHeight ^= mPageWidth;
            mPageWidth ^= mPageHeight;
        }

        //init platform about  like resourcefetchet
        PlatformUtil.getInstance().setmResourceFetcher(new IResourceFetcher() {
            @Override
            public String getString(int id) {
                return MainApplication.getInstance().getString(id);
            }

            @Override
            public String getString(int id, Object... objs) {
                return MainApplication.getInstance().getString(id, objs);
            }

            @Override
            public int getColor(int id) {
                return MainApplication.getInstance().getResources().getColor(id);
            }
        });
    }



    public int dp2pixel(int i) {
        return (int) (0.5F + getResources().getDisplayMetrics().density * (float) i);
    }

    public int getPageWidth() {
        return mPageWidth;
    }

    public int getPageHeight() {
        return mPageHeight;
    }

    public void logOutWithError() {
        if (ThreadUtil.isUIThread()) {
            MessageUtils.showToast(getString(R.string.feedback_sign_in_again));
            logOut(true);
        } else {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    MessageUtils.showToast(getString(R.string.feedback_sign_in_again));
                    logOut(true);
                    countDownLatch.countDown();
                }
            });
        }
    }

    public boolean validateRong() {
        if (!LoginInstance.isLogin()) {
            LogHelper.e("ron", "disconnect");
            RongCloudEvent.DisConnectRong();
            return false;
        }
        return true;
    }

    public void logOut(boolean force) {
        LoginProxy.getInstance().cleanDeviceToken(force);
        LoginInstance.logout(this);
        Intent intent = new Intent(this, LogoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    public void orderMemberIdError() {
        MobclickAgent.onEventEnd(this, "1001");
    }

    public void orderRongMembersizeError() {
        MobclickAgent.onEventEnd(this, "1002");
    }


    public DateFormat getSystemDateFormat() {
        DateFormat dateFormat;
        final String format = Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
        if (TextUtils.isEmpty(format)) {
            dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM);
        } else {
            dateFormat = new SimpleDateFormat(format);
        }
        return dateFormat;
    }


}
